package com.atguigu.tingshu.order.pattern.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.order.pattern.AbstractOrderConfirmPolicy;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component("1002")
public class TrackOrderConfirm extends AbstractOrderConfirmPolicy {

    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Override
    public OrderInfoVo confirm(TradeVo tradeVo, Long userId) {
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        BigDecimal originalAmount = new BigDecimal("0.00");
        BigDecimal orderAmount = new BigDecimal("0.00");
        BigDecimal derateAmount = new BigDecimal("0.00");
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();

        //获取未购买声音列表
        Long trackId = tradeVo.getItemId();
        List<TrackInfo> trackInfoList = albumFeignClient.findWaitBuyTrackList(trackId, tradeVo.getTrackCount()).getData();
        Assert.notNull(trackInfoList, "不存在待结算声音", trackId);

        //4.2 远程调用专辑服务获取，专辑价格（声音单价）声音不支持折扣
        AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(trackInfoList.get(0).getAlbumId()).getData();
        Assert.notNull(albumInfo, "专辑{}不存在", albumInfo.getId());
        BigDecimal price = albumInfo.getPrice();

        //4.3 计算相关价格
        originalAmount = price.multiply(new BigDecimal(trackInfoList.size()));
        orderAmount = originalAmount;

        //4.4 封装订单明细列表
        orderDetailVoList = trackInfoList.stream().map(trackInfo -> {
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(trackInfo.getId());
            orderDetailVo.setItemName("声音：" + trackInfo.getTrackTitle());
            orderDetailVo.setItemUrl(trackInfo.getCoverUrl());
            orderDetailVo.setItemPrice(price);
            return orderDetailVo;
        }).collect(Collectors.toList());

        //封装订单价格信息
        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setOrderAmount(orderAmount);
        orderInfoVo.setDerateAmount(derateAmount);
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);

        orderInfoVo.setItemType(tradeVo.getItemType());

        this.tradeNo(orderInfoVo,userId);
        this.tradeSign(orderInfoVo);

        return orderInfoVo;
    }
}
